//
//  VideoPlayer.m
//  Comic
//
//  Created by Ryan on 16/3/12.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "VideoPlayer.h"

@interface VideoPlayer ()

@property(nonatomic,assign)BOOL isTap;

@property(nonatomic,copy)NSString *url;

@end

@implementation VideoPlayer

+(instancetype)shareInstance{

    static VideoPlayer *player = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        player = [[VideoPlayer alloc]init];
        
    });

    return player;



}


- (void)layoutSubviews{
    [super layoutSubviews];
    
    
    self.playerLayer.frame = _player_imageView.bounds;



}

- (void)setPlayer_imageView:(UIImageView *)player_imageView{

    if (_player_imageView != player_imageView) {
        _player_imageView = player_imageView;
    }


}


- (void)playWithURL:(NSString *)url insert:(UIImageView *)imageView{

    
    self.isTap = 0;
    [self.rePlay setHidden:YES];

    _player_imageView = imageView;
    
    NSLog(@"%f",_player_imageView.frame.size.height);

    _url = url;
    
    //对网址进行编码
   url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //根据网址,创建视频项目对象
    
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
    
    //创建视频播放器对象
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    
    //创建一个播放器承载对象,把播放器放到上面去
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    
    
    self.playerLayer.frame = _player_imageView.bounds;
    
    
    //视频的填充方式
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    //把播放器添加到layer层上
    
    [self.player_imageView.layer insertSublayer:self.playerLayer atIndex:0];

    self.activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    
    
    [self.player_imageView addSubview:_activity];

    
    [self.activity mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.center.mas_equalTo(self.player_imageView);
        
        make.height.width.mas_equalTo(40);
        
        
        
    }];

    [self.activity startAnimating];
    
    [self.player play];
    //            //对播放进度进行设置
    [self addProgress];
    
    [self createView];

  

    
    
    
  
    
   

}


- (void)addProgress{

    
    __weak typeof(self) weakSelf = self;

    //设置成(1,1) 每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        //视频的总时间,将CMT转传承CGFloat
        CGFloat durationTime = CMTimeGetSeconds(weakSelf.playerItem.duration);
        
        //当前时间
        
        CGFloat current = CMTimeGetSeconds(weakSelf.playerItem.currentTime);
        
        //倒计时
        
//        CGFloat rem = durationTime - current;
        
        //总时长
        
        //把时间转换成NSString,在进行赋值
        
        NSString *toltaleT = [NSString stringWithFormat:@"%02d:%02d",(int)durationTime/60,(int)durationTime
                              %60];
        
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60,(int)current%60];
        
        
        //最后给label进行赋值
        
        weakSelf.totalTimeLabel.text = toltaleT;

        weakSelf.currentTimeLabel.text = currentT;
        //让slider叶向前移动
        
        weakSelf.videoSlider.value = current/durationTime;
        
        //保存总时长,用于手动快进的时候
        
        weakSelf.duation = durationTime;
    
        [weakSelf.activity stopAnimating];

    }];
    
}



- (void)createView{
    
  
    self.maskView = [UIView new];
    
    [self.player_imageView addSubview:self.maskView];
    
    self.backView = [UIView new];
    
    self.backView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.6];
    
    [self.player_imageView addSubview:self.backView];
    
  

    self.startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.backView addSubview:self.startButton];
    
    UITapGestureRecognizer *tap = [UITapGestureRecognizer new];
    
    UITapGestureRecognizer *change = [UITapGestureRecognizer new];

    
    [change addTarget:self action:@selector(change:)];
    
    [self.maskView addGestureRecognizer:change];

    
    [self.backView addGestureRecognizer:tap];
    
    self.backView.hidden = YES;
    
    [self.startButton setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
    
    [self.startButton addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.currentTimeLabel = [UILabel new];
    
    self.currentTimeLabel.textColor = [UIColor whiteColor];
    
    self.currentTimeLabel.font = [UIFont systemFontOfSize:12];
    
    
    [self.backView addSubview:self.currentTimeLabel];
    
    
    self.totalTimeLabel = [UILabel new];
    
    self.totalTimeLabel.textColor = [UIColor grayColor];
    
    self.totalTimeLabel.font = [UIFont systemFontOfSize:12];
    
    
    
    
    [self.backView addSubview:self.totalTimeLabel];
    
    
    
    
    self.videoSlider = [UISlider new];
    
    [self.videoSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    
    
    [self.backView addSubview:self.videoSlider];
    
    [self.videoSlider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
    [self.videoSlider addTarget:self action:@selector(sliderEndChange:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchCancel | UIControlEventTouchUpOutside];
    
    self.rePlay = [UIImageView new];
    
    [self.player_imageView addSubview:self.rePlay];
    
    
    [self.rePlay setImage:[UIImage imageNamed:@"player_replay"]];
    
    [self.rePlay setHidden:YES];
    
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.left.right.bottom.mas_equalTo(0);
        
        make.height.mas_equalTo(40);
        
        
    }];
    
    [_maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(0);
//        make.bottom.mas_equalTo(self.backView.mas_bottom);
        
    }];
    
    
    
    [self.startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(5);
        
        make.bottom.mas_equalTo(-5);
        
        make.width.height.mas_equalTo(30);
        
        
    }];
    
    [self.currentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.startButton.mas_right).offset(10);
        
        make.bottom.mas_equalTo(-10);
        
        make.width.mas_equalTo(50);
        
        make.height.mas_equalTo(20);
        
        
    }];
    
    [self.totalTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.left.mas_equalTo(self.currentTimeLabel.mas_right).offset(10);
        
        make.bottom.mas_equalTo(-10);
        
        make.width.mas_equalTo(50);

        make.height.mas_equalTo(20);

    }];
    

    
    [self.videoSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(-5);
        
    }];

    [self.rePlay mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.center.mas_equalTo(self.player_imageView);
        
        make.height.width.mas_equalTo(40);
        
    }];
    
    
    
    
    //监听当前的视频播放情况,只要播放结束,就触发指定方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    

}


- (void)movieEnd:(NSNotification *)notification{
    

    
    [self.rePlay setHidden:NO];
    [self.maskView removeFromSuperview];
    
    
    
    
}


- (void)startAction:(UIButton *)button{
    
    if (button.selected) {
        [_player play];
        [self.startButton setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];

    } else {
        [_player pause];
        [self.startButton setImage:[UIImage imageNamed:@"player_start"] forState:UIControlStateNormal];

        
        
        
    }
    button.selected = !button.selected;

}

- (void)sliderChange:(UISlider *)slider{
    
    
    [self.player pause];
    //获取当前的时间
    double currentTime = self.duation * self.videoSlider.value;
    
    //设置要进行跳转的时间
    
    
    NSString *currentT = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime/60,(int)currentTime%60];

    
    self.currentTimeLabel.text = currentT;


}

- (void)sliderEndChange:(UISlider *)slider{

    double currentTime = self.duation * self.videoSlider.value;
    
    //设置要进行跳转的时间
    
    CMTime drage = CMTimeMake(currentTime, 1);
    
    //对player进行设置
    [self.player seekToTime:drage completionHandler:^(BOOL finished) {
        
        [self.player play];
    }];



}


- (void)change:(UITapGestureRecognizer *)tap{

    if (self.isTap) {
        [UIView animateWithDuration:0.5 animations:^{
            
            [self.backView setHidden:YES];
            
        }];    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
           
            [self.backView setHidden:NO];
            
        }];
        
        
    }
    self.isTap = !self.isTap;
}


- (void)rePlay:(UIButton *)button{
    [self.rePlay setHidden:YES];
    [[VideoPlayer shareInstance] playWithURL:self.url insert:_player_imageView];
}


@end
